define(function (require, exports, module) {
    'use strict';
    var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        notify = require('js/utils/notify'),
        models = require('js/apps/op/models'),
        utils = require('js/utils/tools'),
        app = Backbone.history;
    require('datetimepicker');

    var PayListView = Backbone.View.extend({
        tagName: "div",
        events: {
            'click #search': 'doSearch',
            'click #exportData': 'exportData',
            'click #switchSearchTime': 'changeSearchTime',
        },

        initialize: function (options) {
            this.options = options;
            this.collection = new models.PayOrderCollection();
            this.collection.bind('change remove reset', this.renderWithData, this);
            this.mchCollection = new models.MchCollection();
            this.mchCollection.bind('change reset remove', this.renderWithData, this);
        },
        render: function () {
            this.$el.html("");
            $(window).scrollTop(0);
            return this;
        },
        exportData: function (e) {
            e.preventDefault();
            if (this.collection.total == 0) {
                return;
            }
            if (this.collection.total > 1000) {
                notify.warning('警告', '数据量较大，请耐心等待');
            }
            utils.exportData(this.collection.url, this.options);
            return false;
        },
        changeSearchTime: function () {
            var $item = $('#switchSearchTime');
            if ($item.html() == '下单时间(点击切换)') {
                $item.html('到账时间(点击切换)');
                $('#searchUpdatedAt').show();
                $('#searchCreatedAt').hide().find('input').each(function () {
                    $(this).val('');
                });
            } else {
                $item.html('下单时间(点击切换)');
                $('#searchCreatedAt').show();
                $('#searchUpdatedAt').hide().find('input').each(function () {
                    $(this).val('');
                });
            }
        },
        doSearch: function () {
            var options = {},
                searched = {};
            searched.id = $('#searchId').val();
            searched.out_trade_no = $('#searchOutTradeNo').val();
            searched.third_id = $("#searchThirdId").val();
            searched.mch_id = parseInt($("#searchMchId").val());
            searched.user_id = parseInt($("#searchUserId").val());
            searched.created_at_lower = $("#searchCreatedAtLower").val();
            searched.created_at_upper = $('#searchCreatedAtUpper').val();
            searched.updated_at_lower = $("#searchUpdatedAtLower").val();
            searched.updated_at_upper = $('#searchUpdatedAtUpper').val();
            searched.channel_type = parseInt($('#searchChannelType').val());
            searched.status = parseInt($('#searchPayStatus').val());
            searched.notify_status = parseInt($('#searchNotifyStatus').val());

            if (searched.mch_id != -1) {
                options.mch_id = searched.mch_id;
            }
            if (searched.user_id) {
                options.user_id = searched.user_id;
            }
            if (searched.out_trade_no) {
                options.out_trade_no = searched.out_trade_no;
            }
            if (searched.third_id) {
                options.third_id = searched.third_id;
            }
            if (searched.id) {
                options.id = searched.id;
            }
            if (searched.created_at_lower || searched.created_at_upper) {
                options.created_at = {};
                if (searched.created_at_lower) options.created_at.$gte = searched.created_at_lower;
                if (searched.created_at_upper) options.created_at.$lt = searched.created_at_upper;
            }
            if (searched.updated_at_lower || searched.updated_at_upper) {
                options.updated_at = {};
                if (searched.updated_at_lower) options.updated_at.$gte = searched.updated_at_lower;
                if (searched.updated_at_upper) options.updated_at.$lt = searched.updated_at_upper;
            }
            if (options.created_at) {
                searched.time_field = 'created_at';
            } else if (options.updated_at) {
                searched.time_field = 'updated_at';
            }
            if (searched.channel_type != -1) {
                options.channel_type = searched.channel_type;
            }
            if (searched.status != -1) {
                options.status = searched.status;
            }
            if (searched.notify_status != -1) {
                options.notify_status = searched.notify_status;
            }
            utils.saveSearched('op/pay', searched);
            app.navigate(utils.composeQueryString('#op/pay/', options), {
                trigger: true
            });
        },
        renderWithData: function () {
            this.$el.html(this.template({
                items: this.collection.toJSON(),
                searched: utils.getSearched('op/pay'),
                overview: this.collection.overview,
                mchs: this.mchCollection.toJSON()
            }));
            var that = this;
            $('.refreshStatus').click(function() {
                var data_id = $(this).data('id');
                $.post('/pay/admin/order/'+data_id+'/fresh/').done(function (resp) {
                  var data = resp.data;
                  notify.success('提示', '刷新成功！');
                  that.load();
                }).fail(function (data) {
                  notify.notifyResp(data);
                });
            });
            utils.renderTable('main-list', {
                $orderby: that.options.$orderby || '-created_at',
                sortCallback: function (field) {
                    that.options.$orderby = field;
                    that.options.$page = 1;
                    var newUrl = utils.composeQueryString('#op/pay/', that.options);
                    app.navigate(newUrl, {
                        trigger: true
                    });
                }
            });
            $('[data-type=date]').datetimepicker({
                defaultDate: false,
                format: 'YYYY-MM-DD HH:mm:ss'
            });
            utils.getPaginator(that.options, this.collection.total, '#op/pay/');
            return this;
        },
        load: function () {
            this.mchCollection.fetch({
                reset: true,
                data: {
                    "$size": -1
                },
                error: function (c, r, o) {
                    notify.notifyResp(r);
                },
            });
            this.collection.fetch({
                reset: true,
                data: this.options,
                error: function (c, r, o) {
                    notify.notifyResp(r);
                    $('#content').append('<h4 class="text-muted">无数据</h4>');
                }
            });
        }
    });
    exports.List = Backbone.View.extend({
        el: "#content_wrapper",
        template: "op/PayList.html",
        initialize: function (options) {
            this.options = options;
        },
        render: function () {
            var view = new PayListView(this.options);
            view.template = this.template;
            this.$el.empty();
            this.$el.append(view.render().el);
            view.load();

            return this;
        }
    });

});
